import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
import { DatePipe } from '@angular/common';
import { RechargeOrderService } from '../recharge-order.service';
import { CommonService } from '../../../../services-common/common.service';
import { rechargeOrderStateArrs } from '../recharge-order.pipe';
import { NzModalService } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-order-list',
  templateUrl: './order-list.component.html',
  styleUrls: ['./order-list.component.scss'],
  providers: [DatePipe]
})
export class OrderListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;

  @ViewChild('rechargeFollowRef') rechargeFollowRef: any;

  platformOptions: any = []; // 平台options
  channelOptions: any = []; // 渠道options
  // 规格options 7天、1个月、3个月、6个月、12个月
  specificationsOptions: any = [
    { value: '7天', label: '7天' },
    { value: '1个月', label: '1个月' },
    { value: '3个月', label: '3个月' },
    { value: '6个月', label: '6个月' },
    { value: '12个月', label: '12个月' }
  ];
  searchOptions = [
    { type: 1, labelText: '订单编号', valueKey: 'orderNum', value: '' },
    { type: 1, labelText: '用户', valueKey: 'rechargeNumber', value: '', placeholder: '请输入用户ID/充值账号' },
    {
      type: 2,
      labelText: '订单状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      selectBindKey: { key: 'id', label: 'label' },
      selectOptions: [...rechargeOrderStateArrs],
    },
    {
      type: 2,
      labelText: '平台',
      valueKey: 'platform',
      value: '',
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '渠道',
      valueKey: 'cid',
      value: '',
      selectBindKey: { key: 'content', label: 'name' },
      selectOptions: [],
    },
    {
      type: 2,
      labelText: '品牌',
      valueKey: 'brand',
      value: '',
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
      selectChange: (val: any) => {
        this.brandChange(val);
      }
    },
    {
      type: 2,
      labelText: '商品',
      valueKey: 'goods',
      value: [],
      multiple: true,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: [],
      hide: true
    },
    {
      type: 2,
      labelText: '规格',
      valueKey: 'spec',
      value: [],
      multiple: true,
      selectOptions: this.specificationsOptions,
    },
    { type: 3, labelText: '下单时间', valueKey: ['createBeginTime', 'createEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '付款时间', valueKey: ['payBeginTime', 'payEndTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    tableData: [1],
    loading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跟进Params
  followParams: any = {};
  exportLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private commonService: CommonService,
    private router: Router,
    private datePipe: DatePipe,
    private modal: NzModalService,
    private services: RechargeOrderService
  ) {
  }

  ngOnInit(): void {
    OrderListComponent.updateCache = () => {
      this.init();
    };
    
    this.init();
  }

  init() {
    this.queryDictDatas();
    this.getBrandOptions();
    this.loadTable();
  }

  // 字典查询
  async queryDictDatas() {
    this.platformOptions = await this.commonService.getDictList('channel'); // 平台
    this.channelOptions = await this.commonService.getDictList('iDiy_extension_channel'); // 渠道
    this.searchOptions[3].selectOptions = [...this.platformOptions]; // search 平台
    this.searchOptions[4].selectOptions = [...this.channelOptions]; // search 渠道
  }

  // 查询品牌options
  async getBrandOptions() {
    const res: any = await this.services.getrechargeBrandList();
    if (res.code === 0) {
      this.searchOptions[5].selectOptions = res.data || [];
    }
  }

  // 品牌Change
  brandChange(val: any) {
    let goodsIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'goods');
    if (val) {
      this.searchOptions[goodsIndex].hide = false;
      this.getGoodsOptions(val);
    } else {
      this.searchOptions[goodsIndex].hide = true;
      this.searchOptions[goodsIndex].selectOptions = [];
    }
  }

  // 查询商品options
  async getGoodsOptions(brandId: number) {
    let goodsIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'goods');
    const res: any = await this.services.getRechargeGoodsList(brandId);
    if (res.code === 0) {
      this.searchOptions[goodsIndex].selectOptions = res.data || [];
    }
  }

  async loadTable() {
    let params  = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.queryRechargeOrderList(params);
    this.tableParams.loading = false;
    
    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    let goodsIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'goods');
    this.searchOptions[goodsIndex].hide = true;
    this.searchOptions[goodsIndex].selectOptions = [];
    
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  reviewDetail(item: any) {
    this.router.navigate(['/recharge/rechargeOrderDetail'], {
      queryParams: {
        id: item.id,
        businessNo: item.orderNum
      }
    })
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 字典Filter
  dictFilter(keVal: any, arr: Array<any>) {
    let tempObj: any = {};
    if (arr.length) {
      tempObj = arr.find((item: any) => item.content == keVal);
    }
    return tempObj?.name || '-';
  }

  // 跟进操作
  followModal(item: any) {
    this.followParams = {
      type: 2,
      businessNo: item.orderNum
    }
    this.rechargeFollowRef.isModelVisible = true;
  }

  exportTable() {
    if (!this.tableParams.tableData.length) {
      this.message.warning('当前无数据可导出');
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.searchParams
        }
        this.exportLoading = true;
        const res: any = await this.services.exportRechargeOrder(params);
        this.exportLoading = false;
    
        if (res.type == 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '充值专区订单');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  async cancelOrder(item: any) {
    let params = {
      id: item.id
    }
    const res: any = await this.services.cancelRechargeOrder(params);
    if (res.code === 0) {
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }
}
